package app

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/lab-online/pkg/color"
	"github.com/lab-online/pkg/logger"
)

func (app *Context) buildServer(addr string) {
	app.server = &http.Server{
		Addr:           addr,
		Handler:        app.engine,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
}

func (app *Context) Listening(addr string) {
	colorfulAddr := color.Style(addr, color.ColorBlue, color.FontUnderline)
	logger.Info("server will listening on", colorfulAddr)
	if err := app.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		logger.Error(err.Error())
	}
}

// Shutdown 安全关闭服务
func (app *Context) Shutdown() {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	logger.Info("shutdown server ...")
	defer logger.Info("server exited")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := app.server.Shutdown(ctx); err != nil {
		logger.Error("shutdown failed:", err)
	}

	logger.Info("cancel context ...")
	for _, cancel := range app.effects {
		cancel()
	}
}
